<template>
    <div>
        <el-form :model="loginForm" :rules="loginRules" ref="loginFormRef" size="large">
            <el-form-item prop="username">
                <el-input v-model="loginForm.username" :placeholder="placeholderUserName" clearable>
                    <template #prefix>
                        <user class="prefix-icon-style" color="lightblue" />
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item prop="password">
                <el-input
                    type="password"
                    v-model="loginForm.password"
                    :placeholder="placeholderPassword"
                    clearable
                    show-password
                    autocomplete="new-password"
                >
                    <template #prefix>
                        <lock class="prefix-icon-style" color="yellow" />
                    </template>
                </el-input>
            </el-form-item>
            <el-form-item class="login-captcha" prop="captcha">
                <el-input v-model="loginForm.captcha" :placeholder="placeholderCaptcha">
                    <template #prefix>
                        <key class="prefix-icon-style" color="lightgreen" />
                    </template>
                </el-input>
                <img src="@/assets/images/captcha.gif" />
            </el-form-item>
        </el-form>
        <div class="login-btn">
            <el-button type="default" round size="large" @click="resetForm(loginFormRef)">注册</el-button>
            <el-button type="primary" round size="large" :icon="UserFilled" @click="login(loginFormRef)">登录</el-button>
        </div>
    </div>
</template>

<script setup lang="ts" name="LoginForm">
import type { ElForm } from "element-plus";
import { ElNotification } from "element-plus";
import { hookI18n } from "@/hooks/hookI18n";
import { useUserStore } from "@/store";
import { router, initDynamicRouter, resetRouter } from "@/router";
import { UserFilled } from "@element-plus/icons-vue";
import { RouterConfig } from "@/config";
import { useAxiosApi } from "@/api";
import { useTabsStore } from "@/store/modules/tabs";
import { useKeepAliveStore } from "@/store/modules/keep_alive";

const { t } = hookI18n();
const api = useAxiosApi();
const userStore = useUserStore();
const tabsStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();

const HOME_URL = RouterConfig.HOME_URL;

const placeholderUserName = t("login.placeholderUserName") + ": admin";
const placeholderPassword = t("login.placeholderPassword") + ": 123456";
const placeholderCaptcha = t("permission.captcha");

type FormInstance = InstanceType<typeof ElForm>;
const loginFormRef = ref<FormInstance>();

const loginForm = reactive({
    username: "",
    password: "",
    captcha: "",
});

const loginRules = reactive({
    username: [{ required: false, message: t("login.placeholderUserName"), trigger: "blur" }],
    password: [{ required: false, message: t("login.placeholderPassword"), trigger: "blur" }],
    captcha: [{ required: false, message: t("common.required"), trigger: "blur" }],
});

const loading = ref(false);

/**
 * 登录
 * @param form
 */
const login = (form: FormInstance | undefined) => {
    (form as FormInstance).validate(async (valid: boolean) => {
        if (!valid) {
            ElNotification({
                title: "title",
                message: "不能登录。。。",
                duration: 1000,
            });
            return;
        }

        try {
            loading.value = true;

            // 1.执行登录接口
            // const { data } = await api.loginApi({ ...loginForm, password: Md5.hashStr(loginForm.password) });
            // console.log(`lf_data = ${data}`)
            // userStore.setToken(data.access_token);
            // 登录成功设置令牌
            userStore.setToken("123");

            // 2.添加动态路由
            await initDynamicRouter();

            // 3.清空 tabs、keepAlive 保留的数据
            tabsStore.closeMultipleTab();
            keepAliveStore.setKeepAliveName();

            // 4.跳转到首页
            router.push(HOME_URL);

            // ElNotification({
            //     title: 'title',
            //     message: "欢迎登录 Honover Admin",
            //     type: "success",
            //     duration: 3000
            // });
        } finally {
            loading.value = false;
        }
    });
};

/**
 * 重置 form
 * @param formEl
 */
const resetForm = (formEl: FormInstance | undefined) => {
    if (formEl) {
        formEl.resetFields();
    }
};

/**
 * 监听 onkeydown 事件（调用登录）
 */
onMounted(() => {
    document.onkeydown = (e: KeyboardEvent) => {
        e = (window.event as KeyboardEvent) || e;
        if (e.code === "Enter" || e.code === "enter" || e.code === "NumpadEnter") {
            if (!loading.value) {
                login(loginFormRef.value);
            }
        }
    };
});
</script>

<style scoped lang="scss">
$prefix-icon_size: 1.5em;
$prefix-icon-width: $prefix-icon_size;
$prefix-icon-height: $prefix-icon_size;

img {
    padding: 15px;
    // width: 80%;
    height: 32px;
}

.login-captcha {
    :deep(.el-input) {
        width: 200px;
    }
}

.prefix-icon-style {
    width: $prefix-icon-width;
    height: $prefix-icon-height;
    margin-right: 8px;
}

.login-btn {
    display: flex;
    justify-content: space-between;
    width: 100%;
    margin-top: 50px;
    white-space: nowrap;

    .el-button {
        width: 185px;
    }
}
</style>
